package com.gagakuai.transport.channel.socket.nio;

import com.gagakuai.transport.channel.socket.InternetProtocolFamily;
import com.gagakuai.transport.channel.socket.ServerSocketChannelConfig;
import com.gagakuai.utils.SelectorProviderUtil;

import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.channels.SelectionKey;
import java.nio.channels.spi.SelectorProvider;

/*
 * @description: 包装nio的SeverSocketChannel
 * @author: houhong
 * @create: 2024-03-18 23:59
 */
public class NioServerSocketChannel extends AbstractNioMessageChannel implements ServerSocketChannel {


    /*
     *
     *  来自java的包-获取一个多路复用器工厂
     */
    private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider();

    private static final Method OPEN_SERVER_SOCKET_CHANNEL_WITH_FAMILY =
            SelectorProviderUtil.findOpenMethod("openServerSocketChannel");


    private static java.nio.channels.ServerSocketChannel newChannel(SelectorProvider provider, InternetProtocolFamily family) {


        try {

            java.nio.channels.ServerSocketChannel channel = SelectorProviderUtil.newChannel(OPEN_SERVER_SOCKET_CHANNEL_WITH_FAMILY, provider, family);

            return channel == null ? provider.openServerSocketChannel() : channel;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }


    private final ServerSocketChannelConfig config;



    /*=============================================构造器=========================================================*/

    public NioServerSocketChannel() {


        this(DEFAULT_SELECTOR_PROVIDER);
    }


    public NioServerSocketChannel(SelectorProvider provider) {


        this(provider, null);
    }


    public NioServerSocketChannel(SelectorProvider provider, InternetProtocolFamily family) {

        this(newChannel(provider, family));
    }


    /*
     *
     *   将 java.nio的ServerSocketChannel包装一下 -> 变为  NioServerSocketChannel
     *
     *
     */
    public NioServerSocketChannel(java.nio.channels.ServerSocketChannel channel) {

        super(null, channel, SelectionKey.OP_ACCEPT);

        config = new NioServerSocketChannelConfig(this, javaChannel().socket());
    }



    private class  NioServerSocketChannelConfig extends


}


